﻿using Digitalmes.Infrastructure.Scada.Handlers;
using ThingsEdge.Contracts;
using ThingsEdge.Router.Forwarders;

namespace Digitalmes.Infrastructure.Scada.Forwarders;

/// <summary>
/// 通知消息处理。
/// </summary>
internal sealed class NativeNoticeForwarder(IServiceScopeFactory serviceScopeFactory,
    ILogger<NativeNoticeForwarder> logger) : INotificationForwarder
{
    private static readonly Dictionary<string, Type> SingleHandlerMap = new()
    {
        { TagDefinition.PLC_Archive_Inplace, typeof(ArchiveHandler) },
        { TagDefinition.PLC_Realtime_Sign, typeof(RealtimeHandler) },
    };

    public async Task PublishAsync(RequestMessage message, PayloadData? lastMasterPayloadData, CancellationToken cancellationToken = default)
    {
        var self = message.Self();
        if (SingleHandlerMap.TryGetValue(self.TagName, out var type))
        {
            using var scope = serviceScopeFactory.CreateScope();
            var handler = (IScadaNoticeHandler)scope.ServiceProvider.GetRequiredService(type);
            await handler.HandleAsync(message, cancellationToken);
        }
        else
        {
            logger.LogWarning("请求的标记名称 {TagName} 必须属于 {@Tags} 其中的一种。", self.TagName, SingleHandlerMap.Keys);
        }
    }
}
